package com.lanhai.system;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

import com.lanhai.MainAction;
import com.lanhai.action.AgvDispatchAction;


/**
 * 监听UDP端口
 * @author liangmin
 *
 */
public class Accept4Agv implements Runnable {
	
	private MainAction mainAction;
	private int port;
	public static DatagramSocket ds = null;
	
	public Accept4Agv(MainAction mainAction, int port){
		this.mainAction = mainAction;
		this.port = port;
	}
	
	public void run() {	
		
		try{
			InetAddress is = InetAddress.getByName(mainAction.main.localIp);
//			ds = new DatagramSocket(port,is);
			ds = new DatagramSocket(port);
		}catch(Exception e){
			e.printStackTrace();
			System.out.println("已经运行了一个实例，退出!");
			System.exit(0);
		}
		boolean isReceive = true;
//		SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-DD HH:mm:ss:SSS");
		while(isReceive){
			try{
				byte buf[] = new byte[12];
				DatagramPacket dp = new DatagramPacket(buf, buf.length);	
				//String timeStr = sdf.format(new Date());
				//System.out.println("port 5000 ready,time:" + timeStr);				
				ds.receive(dp);
				AgvDispatchAction agvAction = mainAction.agvAction;
				String ipAddress = dp.getAddress().getHostAddress();
				agvAction.handle(buf);
								
			}catch(Exception e){
				e.printStackTrace();
				isReceive = false;
			}
		}			
		ds.close();
		System.out.println("UDP" + port + "端口关闭！！！");
	}
}
